<template>
    <table border="1" class="my-table">
        <thead>
            <tr>
                <th v-for="info of tHead" :key="info.key">
                {{ info.text }}
                </th>
            </tr>
        </thead>
    <tbody>
    <tr v-for="(item,index) of tBody" key="item.id">
    <td 
    v-for="(value,key) of item" 
    :key="key"
    @click.stop="showEditInput($event,key,index)"
    >{{ value }}</td>
    </tr>
    </tbody>
    </table>
</template>
<script setup>
import { createApp, toRefs,ref,reactive } from 'vue'
import EditInput from './EditInput.vue';
//创建一个应用 放到dom节点中去 写组件/插件用createApp比较好
let editInputApp = null // 这个作用域范围内

const state = reactive({
    key:'',
    value:'',
    index:-1,
    text:''
})

const props = defineProps({
    data:{
        type:Object,
        default:()=>({
            tHead:[],
            tBody:[]
        })
    }
})

const emit = defineEmits(['submit'])
const {tHead, tBody} = toRefs(props.data)
const showEditInput = (event,key,index)=>{
    editInputApp&& removeEditInputApp(editInputApp)
   if(!checkEditable(key)) return;
    const target = event.target
    const oFrag = document.createDocumentFragment()
    editInputApp = createApp(EditInput,{
        value:target.textContent,
        setValue
    })
    if(editInputApp){
        editInputApp.mount(oFrag)
        target.appendChild(oFrag)
        target.querySelector('.edit-input').select()
    }
    setData({index,key,text:findText(key)})
}
const setValue =(value)=>{
    state.value = value
    emit('submit',{...state},removeEditInputApp)
}
const setData = ({index,key,text, value=''})=>{
    state.index = index;
    state.key=key;
    state.text=text;
    state.value=value;
}
const findText = (key)=>{
    const { text } = tHead.value.find(item => item.key === key)
    return text
}
const checkEditable = (key)=>{

    // 找到这一项，返回editable的值true/false
    const { editable} = tHead.value.find(item => item.key ===key)
    return editable
}
const removeEditInputApp = ()=>{
    editInputApp && editInputApp.unmount()
    setData({
        index:-1,
        key:'',
        text:'',
        value:''
    })
}
window.addEventListener('click',removeEditInputApp,false)

</script>
<style lang="scss" scoped>
.my-table{
    width: 100%;
    border-collapse: collapse;
    tr{
      height: 44px;
        td{
        border: 1px solid black;
        position: relative;
        text-align: center;
        cursor: pointer;
        }
     
    }
}
</style>